package cars

import (
	"FYKJ_Admin/models/auth"
	"FYKJ_Admin/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"math"
	"strings"
)

type CarsController struct {
	beego.Controller
}
//车辆列表获取
func (c *CarsController) List()  {
	o := orm.NewOrm()

	qs := o.QueryTable("sys_cars")

	cars_data := []auth.Cars{}

	// 每页显示的条数
	pagePerNum := 8
	// 当前页
	currentPage,err := c.GetInt("page")
	if err != nil {   // 说明没有获取到当前页
		currentPage = 1
	}

	offsetNum := pagePerNum * (currentPage - 1)


	kw := c.GetString("kw")
	var count int64 = 0

	ret := fmt.Sprintf("当前页;%d,查询条件：%s",currentPage,kw)
	logs.Info(ret)
	if kw != ""{   // 有查询条件的
		// 总数
		count,_ = qs.Filter("is_delete",0).Filter("car_name__contains",kw).Count()
		qs.Filter("is_delete",0).Filter("car_name__contains",kw).Limit(pagePerNum).Offset(offsetNum).RelatedSel().All(&cars_data)
	}else {
		count,_ = qs.Filter("is_delete",0).Count()
		qs.Filter("is_delete",0).Limit(pagePerNum).Offset(offsetNum).RelatedSel().All(&cars_data)

	}


	// 总页数
	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))


	prePage := 1
	if currentPage == 1{
		prePage = currentPage
	}else if currentPage > 1{
		prePage = currentPage -1
	}

	nextPage := 1
	if currentPage < countPage {
		nextPage = currentPage + 1
	}else if currentPage >= countPage {
		nextPage = currentPage
	}

	page_map := utils.Paginator(currentPage,pagePerNum,count)
	c.Data["cars_data"] = cars_data
	c.Data["prePage"] =prePage
	c.Data["nextPage"] = nextPage
	c.Data["currentPage"] = currentPage
	c.Data["countPage"] = countPage
	c.Data["count"] = count
	c.Data["page_map"] = page_map
	c.Data["kw"] = kw
	c.TplName = "cars/cars_list.html"

}
//车辆添加
func (c *CarsController) ToAdd()  {
	o := orm.NewOrm()
	qs := o.QueryTable("sys_cars_brand")
	cars_brand := []auth.CarBrand{}
	qs.Filter("is_delete",0).All(&cars_brand)
	c.Data["cars_brand"] = cars_brand
	c.TplName = "cars/cars_add.html"

}
//车辆添加
func (c *CarsController) DoAdd()  {
	cars_brand_id,_ := c.GetInt("cars_brand_id")
	car_name := c.GetString("car_name")
	is_active,_ := c.GetInt("is_active")
	o := orm.NewOrm()

	cars_brand := auth.CarBrand{SysId:cars_brand_id}
	cars_data := auth.Cars{
		CarName:car_name,
		CarBrand:&cars_brand,
		IsActive:is_active,
		Status:1,

	}
	_,err := o.Insert(&cars_data)

	message_map := map[string]interface{}{}
	if err != nil {
		message_map["code"] = 10001
		message_map["msg"] = "添加失败"
	}

	message_map["code"] = 200
	message_map["msg"] = "添加成功"
	c.Data["json"] = message_map
	c.ServeJSON()


}

//车辆列表停用启用
func (c *CarsController) IsActive() {
	is_active,_ := c.GetInt("is_active_val")
	sys_id,_ := c.GetInt("sys_id")
	o := orm.NewOrm()
	qs := o.QueryTable("sys_cars").Filter("sys_id",sys_id)
	message_map := map[string]interface{}{}
	if is_active == 1 {
		qs.Update(orm.Params{
			"is_active": 2,
		})
		ret := fmt.Sprintf("车辆列表停用/启用功能，车辆id:%d,停用成功",sys_id)
		logs.Info(ret)
		message_map["msg"] = "停用成功"
	}else if is_active == 2 {
		qs.Update(orm.Params{
			"is_active": 1,
		})
		ret := fmt.Sprintf("车辆列表停用/启用功能，车辆id:%d,启用成功",sys_id)
		logs.Info(ret)
		message_map["msg"] = "启用成功"
	}

	c.Data["json"] = message_map
	c.ServeJSON()
}
//车辆品牌管理删除
func (c *CarsController) Delete() {

	sys_id,_ := c.GetInt("sys_id")
	is_delete_val,_ := c.GetInt("is_delete_val")
	o :=orm.NewOrm()
	// 直接delete删除物理删除
	//o.QueryTable("sys_user").Filter("SysId",SysId).Delete()
	//逻辑删除，修改状态
	qs := o.QueryTable("sys_cars").Filter("sys_id",sys_id)
	message_map := map[string]interface{}{}
	if is_delete_val ==0 {
		qs.Update(orm.Params{
			"is_delete": 1,
		})
		ret := fmt.Sprintf("车辆删除功能，车辆ID:%d,删除成功",sys_id)
		logs.Info(ret)
		message_map["msg"] = "删除成功！"
	}
	c.Data["json"] = message_map
	c.ServeJSON()
	// 重定向页面（刷新页面）
	//u.Redirect(beego.URLFor("UserController.List"),302)
}

//车辆品牌管理批量删除
func (c *CarsController) MuliDelete() {
	ids := c.GetString("ids")
	//得到的结果"3,7,8,9",需要截取掉两边引号为 3,7,8,9
	car_ids :=ids[1:len(ids)-1]
	//，切割符号为逗号
	id_arr := strings.Split(car_ids,",")
	o := orm.NewOrm()
	qs := o.QueryTable("sys_cars")
	for _, v := range id_arr{
		//字符串转int64
		id_int := utils.StrToInt(v)
		qs.Filter("sys_id",id_int).Update(orm.Params{
			"is_delete":1,
		})
	}
	ret :=fmt.Sprintf("车辆删除功能，批量删除成功：车辆ids:%s;",ids)
	logs.Info(ret)
	c.Data["json"] = map[string]interface{}{"code":200,"msg":"批量删除成功！"}
	c.ServeJSON()
}

//车辆品牌管理编辑
func (c *CarsController) ToEdit()  {
	sys_id,_ := c.GetInt("sys_id")
	o := orm.NewOrm()
	//定义一个容器
	cars_data := auth.Cars{}
	o.QueryTable("sys_cars").Filter("sys_id",sys_id).RelatedSel().One(&cars_data)

	//Exclude 排除
	car_brand := []auth.CarBrand{}
	o.QueryTable("sys_cars_brand").Exclude("sys_id",cars_data.CarBrand.SysId).All(&car_brand)

	c.Data["cars_data"] =cars_data
	c.Data["car_brand"] =car_brand
	c.TplName = "cars/cars_edit.html"

}
//车辆品牌管理编辑
func (c *CarsController) DoEdit()  {

	sys_id,_ := c.GetInt("car_id")
	car_name := c.GetString("car_name")
	car_brand_id,_ := c.GetInt("car_brand_id")
	is_active,_ := c.GetInt("is_active")

	o := orm.NewOrm()
	qs := o.QueryTable("sys_cars")
	_,err := qs.Filter("sys_id",sys_id).Update(orm.Params{
		"car_name":car_name,
		"car_brand_id":car_brand_id,
		"is_active":is_active,
	})
	message_map := map[string]interface{}{}
	if err != nil {
		ret_addinfo :=fmt.Sprintf("添加数据出错，添加信息：car_name%s|car_brand_id%d|is_active%d|", car_name,car_brand_id,is_active)
		ret :=fmt.Sprintf("添加数据出错，错误信息：%v",err)
		logs.Error(ret_addinfo)
		logs.Error(ret)
		message_map["code"] = 10001
		message_map["msg"] = "更新失败"
	}
	message_map["code"] = 200
	message_map["msg"] = "更新成功"

	c.Data["json"] = message_map
	c.ServeJSON()

}


